<template>
  <div class="white-list-management">
    <!-- 统计卡片区域 -->
    <el-card class="stats-card" :body-style="{ padding: '15px' }">
      <h2 class="section-title">📊 关键词统计</h2>
      <div class="stats-container">
        <StatisticCard
          label="部门总数"
          :value="statistics.totalDepartments.toString()"
          icon="el-icon-office-building"
          type="primary"
        />
        <StatisticCard
          label="关键词总数"
          :value="statistics.totalKeywords.toString()"
          icon="el-icon-files"
          type="success"
        />
        <StatisticCard
          label="本月命中"
          :value="statistics.monthlyHits.toLocaleString()"
          icon="el-icon-hit"
          type="warning"
        />
        <StatisticCard
          label="平均权重"
          :value="statistics.averageWeight.toFixed(2)"
          icon="el-icon-data-line"
          type="info"
        />
      </div>
    </el-card>

    <!-- 筛选区域 -->
    <el-card class="filter-card" :body-style="{ padding: '15px' }">
      <div v-if="isFilterExpanded" class="filter-content">
        <DynamicForm
          ref="searchFormRef"
          v-model="filterForm"
          :form-config="filterFormConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </el-card>

    <!-- 关键词列表 -->
    <el-card class="table-card" :body-style="{ padding: '15px' }">
      <div class="list-header">
        <div class="header-left">
          <el-button type="primary" @click="openAddModal">
            + 新增关键词
          </el-button>
          <el-button type="success" @click="openBatchImportModal">
            批量导入
          </el-button>
          <el-button type="warning" @click="handleExport"> 批量导出 </el-button>
        </div>
        <div class="header-right">
          <span class="sort-label">排序:</span>
          <el-select
            v-model="filterForm.sort_by"
            size="small"
            style="width: 120px; margin-right: 10px"
            @change="handleSearch"
          >
            <el-option label="按部门" value="department" />
            <el-option label="按权重" value="weight" />
            <el-option label="按命中率" value="hit_count" />
            <el-option label="按添加时间" value="created_time" />
          </el-select>
          <el-select
            v-model="filterForm.sort_order"
            size="small"
            style="width: 80px"
            @change="handleSearch"
          >
            <el-option label="升序" value="asc" />
            <el-option label="降序" value="desc" />
          </el-select>
        </div>
      </div>

      <div v-loading="loading" class="department-list">
        <div
          v-for="dept in departmentList"
          :key="dept.department"
          class="department-group"
        >
          <div
            class="department-header"
            @click="toggleDepartment(dept.department)"
          >
            <i
              :class="
                expandedDepartments.has(dept.department)
                  ? 'el-icon-arrow-down'
                  : 'el-icon-arrow-right'
              "
              class="expand-icon"
            ></i>
            <span class="department-name">📂 {{ dept.department }}</span>
            <span class="keyword-count"
              >({{ dept.keyword_count }}个关键词)</span
            >
            <span class="expand-text">
              {{ expandedDepartments.has(dept.department) ? "收起" : "展开" }}
            </span>
          </div>

          <div
            v-show="expandedDepartments.has(dept.department)"
            class="keywords-table-wrapper"
          >
            <DynamicTable
              :data="dept.keywords"
              :columns="tableColumns"
              :loading="false"
              border
              row-key="id"
            >
              <template #action="{ row }">
                <el-button
                  size="small"
                  @click="openEditModal(row)"
                  type="primary"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  @click="handleDelete(row)"
                  type="danger"
                >
                  删除
                </el-button>
              </template>
            </DynamicTable>
          </div>
        </div>

        <el-empty
          v-if="!loading && departmentList.length === 0"
          description="暂无数据"
        />
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="pagination.total > 0">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="pagination.pageSizes"
          :total="pagination.total"
          :layout="pagination.layout"
          :background="pagination.background"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑关键词弹窗 -->
    <AddEditModal
      v-model="addEditVisible"
      :keyword="currentKeyword"
      :is-edit="isEditMode"
      :department-options="departmentOptions"
      @save="handleSaveKeyword"
    />

    <!-- 批量导入弹窗 -->
    <BatchImportModal
      v-model="batchImportVisible"
      :departments="departmentOptions"
      @confirm-import="handleBatchImportSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import StatisticCard from "./components/StatisticCard.vue";
import {
  getKeywords,
  createKeyword,
  updateKeyword,
  deleteKeyword,
  exportKeywords,
} from "../../servers";
import AddEditModal from "./components/AddEditModal.vue";
import BatchImportModal from "./components/BatchImportModal.vue";

// 页面状态
const isFilterExpanded = ref(true);
const loading = ref(false);
const addEditVisible = ref(false);
const isEditMode = ref(false);
const currentKeyword = ref<any>({});
const batchImportVisible = ref(false);

// 部门选项（从接口获取后动态更新）
const departmentOptions = ref<Array<{ label: string; value: string }>>([]);

// 部门列表数据（按部门分组）
const departmentList = ref<
  Array<{
    department: string;
    keyword_count: number;
    keywords: Array<{
      id: number;
      keyword: string;
      weight: number;
      monthly_hits: number;
      total_hits: number;
      created_at: string;
      updated_at: string | null;
      created_by: string;
      remark: string | null;
    }>;
  }>
>([]);

// 部门展开状态
const expandedDepartments = ref<Set<string>>(new Set());

// 统计信息
const statistics = reactive({
  totalDepartments: 0,
  totalKeywords: 0,
  monthlyHits: 0,
  averageWeight: 0,
});

// 筛选表单
const searchFormRef = ref<DynamicFormInstance>();
const filterForm = reactive({
  department: "",
  keyword: "",
  sort_by: "department",
  sort_order: "asc",
});

// 筛选表单配置
const filterFormConfig = computed<FormItemConfig[]>(() => [
  {
    key: "department",
    name: "部门筛选",
    type: "select",
    placeholder: "全部部门",
    params: { clearable: true },
    options: departmentOptions.value,
    col: { span: 6 },
  },
  {
    key: "keyword",
    name: "关键词搜索",
    type: "input",
    placeholder: "请输入关键词",
    col: { span: 6 },
  },
  {
    key: "sort_by",
    name: "排序方式",
    type: "select",
    placeholder: "请选择排序方式",
    params: { clearable: false },
    options: [
      { label: "按部门排序", value: "department" },
      { label: "按权重排序", value: "weight" },
      { label: "按命中率排序", value: "hit_count" },
      { label: "按添加时间排序", value: "created_time" },
    ],
    col: { span: 6 },
  },
  {
    key: "sort_order",
    name: "排序方向",
    type: "select",
    placeholder: "请选择排序方向",
    params: { clearable: false },
    options: [
      { label: "升序", value: "asc" },
      { label: "降序", value: "desc" },
    ],
    col: { span: 6 },
  },
]);

// 表格列配置
const tableColumns: TableColumn[] = [
  { label: "关键词", prop: "keyword", minWidth: 120 },
  {
    label: "权重",
    prop: "weight",
    minWidth: 80,
    align: "center",
    formatter: (row) => {
      return `<span class="weight-value">${row.weight}</span>`;
    },
  },
  {
    label: "本月命中",
    prop: "monthly_hits",
    minWidth: 100,
    align: "center",
    formatter: (row) => {
      return `${row.monthly_hits}次`;
    },
  },
  {
    label: "累计命中",
    prop: "total_hits",
    minWidth: 100,
    align: "center",
    formatter: (row) => {
      return `${row.total_hits}次`;
    },
  },
  {
    label: "添加时间",
    prop: "created_at",
    minWidth: 160,
    formatter: (row) => {
      return row.created_at ? row.created_at.substring(0, 10) : "-";
    },
  },
  {
    label: "操作",
    width: 150,
    fixed: "right",
    slot: "action",
  },
];

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
});

// 获取关键词列表和统计数据
const fetchKeywordList = async (values?: any) => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      ...values,
    };

    const { data } = await getKeywords(params);
    if (data) {
      if (data.statistics) {
        statistics.totalDepartments = data.statistics.total_departments || 0;
        statistics.totalKeywords = data.statistics.total_keywords || 0;
        statistics.monthlyHits = data.statistics.monthly_hits || 0;
        statistics.averageWeight = data.statistics.average_weight || 0;
      }

      if (data.departments && Array.isArray(data.departments)) {
        departmentList.value = data.departments;

        const departments = new Set<string>();
        data.departments.forEach((dept: any) => {
          if (dept.department) {
            departments.add(dept.department);
          }
        });
        departmentOptions.value = Array.from(departments).map((dept) => ({
          label: dept,
          value: dept,
        }));

        if (expandedDepartments.value.size === 0) {
          data.departments.forEach((dept: any) => {
            if (dept.department) {
              expandedDepartments.value.add(dept.department);
            }
          });
        }
      }

      if (data.pagination) {
        pagination.total = data.pagination.total || 0;
        pagination.currentPage = data.pagination.page || 1;
        pagination.pageSize = data.pagination.page_size || 20;
      }
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取关键词列表失败");
  } finally {
    loading.value = false;
  }
};

// 切换部门展开/收起
const toggleDepartment = (department: string) => {
  if (expandedDepartments.value.has(department)) {
    expandedDepartments.value.delete(department);
  } else {
    expandedDepartments.value.add(department);
  }
};

// 筛选操作
const handleReset = () => {
  searchFormRef.value?.resetFields();
  filterForm.department = "";
  filterForm.keyword = "";
  filterForm.sort_by = "department";
  filterForm.sort_order = "asc";
  pagination.currentPage = 1;
  fetchKeywordList();
};

const handleSearch = (values: any) => {
  pagination.currentPage = 1;
  fetchKeywordList(values);
};

// 分页操作
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchKeywordList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchKeywordList();
};

// 弹窗控制
const openAddModal = () => {
  isEditMode.value = false;
  currentKeyword.value = {};
  addEditVisible.value = true;
};

const openEditModal = (row: any) => {
  // 从部门列表中查找该关键词所属的部门
  let department = "";
  for (const dept of departmentList.value) {
    const keyword = dept.keywords.find((k) => k.id === row.id);
    if (keyword) {
      department = dept.department;
      break;
    }
  }

  isEditMode.value = true;
  currentKeyword.value = {
    id: row.id,
    department: department,
    keyword: row.keyword || "",
    weight: row.weight || 0.8,
    remark: row.remark || "",
  };
  addEditVisible.value = true;
};

// 保存关键词（新增/编辑）
const handleSaveKeyword = async (formData: any) => {
  try {
    loading.value = true;
    if (isEditMode.value) {
      // 编辑模式
      const result = await updateKeyword(formData.id, {
        weight: formData.weight,
        remark: formData.remark,
      });
      ElMessage.success(result?.message || "关键词更新成功");
    } else {
      // 新增模式
      const result = await createKeyword({
        department: formData.department,
        keyword: formData.keyword,
        weight: formData.weight,
        remark: formData.remark,
      });
      ElMessage.success(result?.message || "关键词创建成功");
    }
    addEditVisible.value = false;
    fetchKeywordList();
  } catch (error: any) {
    ElMessage.error(error?.message || "保存关键词失败");
  } finally {
    loading.value = false;
  }
};

// 删除关键词
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除关键词【${row.keyword}】吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const result = await deleteKeyword(row.id);
    ElMessage.success(result?.message || "关键词删除成功");
    fetchKeywordList();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "删除关键词失败");
    }
  } finally {
    loading.value = false;
  }
};

// 打开批量导入弹窗
const openBatchImportModal = () => {
  batchImportVisible.value = true;
};

// 批量导入成功回调
const handleBatchImportSuccess = () => {
  fetchKeywordList();
};

// 批量导出
const handleExport = async () => {
  try {
    loading.value = true;
    const params: any = {};
    if (filterForm.department) {
      params.department = filterForm.department;
    }
    if (filterForm.keyword) {
      params.keyword = filterForm.keyword;
    }

    const blob = await exportKeywords(params);

    // 创建下载链接
    const url = URL.createObjectURL(blob as any);
    const a = document.createElement("a");
    a.href = url;
    const date = new Date().toISOString().split("T")[0].replace(/-/g, "");
    a.download = `关键词导出_${date}.xlsx`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    ElMessage.success("导出成功");
  } catch (error: any) {
    ElMessage.error(error?.message || "导出失败");
  } finally {
    loading.value = false;
  }
};

// 初始化
onMounted(() => {
  fetchKeywordList();
});
</script>

<style scoped lang="scss">
.white-list-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .stats-card,
  .filter-card,
  .table-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #444;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .stats-container {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .filter-content {
    padding: 5px 0;
  }

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;

    .list-title {
      font-size: 16px;
      font-weight: 500;
      margin: 0;
      color: #303133;
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 10px;

      .sort-label {
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .department-list {
    min-height: 200px;
  }

  .department-group {
    margin-bottom: 15px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    overflow: hidden;

    .department-header {
      display: flex;
      align-items: center;
      padding: 12px 15px;
      background-color: #f5f7fa;
      cursor: pointer;
      user-select: none;
      transition: background-color 0.2s;

      &:hover {
        background-color: #ecf5ff;
      }

      .expand-icon {
        margin-right: 8px;
        color: #909399;
        font-size: 14px;
      }

      .department-name {
        font-weight: 500;
        color: #303133;
        font-size: 14px;
      }

      .keyword-count {
        margin-left: 8px;
        color: #909399;
        font-size: 13px;
      }

      .expand-text {
        margin-left: auto;
        color: #909399;
        font-size: 12px;
      }
    }

    .keywords-table-wrapper {
      padding: 0;
      background-color: #fff;
    }
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

:deep(.weight-value) {
  font-weight: 500;
  color: #409eff;
}
</style>
